import { Monster } from "../08_module_TS/MonsterTS";

// Learn TypeScript:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    @property(cc.Label)
    hint: cc.Label = null;

    @property(cc.Prefab)
    monsterPrefab: cc.Prefab;

    @property(cc.Vec2)
    regionOrign:cc.Vec2;

    @property(cc.Vec2)
    regionSize:cc.Vec2;

    _pool:cc.NodePool;

    _count:number=0;

    // LIFE-CYCLE CALLBACKS:

    onLoad () {

        this.schedule(this.generateNode,2);
    //新建一个nodePool
     this._pool = new cc.NodePool('PoolHandler');

     this._count=0;

    }

    generateNode(){

        let monster=this._pool.get();

        //没有，则创建一个monster
        if(monster===null){

            monster=cc.instantiate(this.monsterPrefab) as cc.Node;

            this._count++;

            this.hint.string='Node Crated:'+this._count;

            monster.addComponent('PoolHandler');
        }
        monster.x=this.regionOrign.x+Math.floor(Math.random()*this.regionSize.x);

        monster.y=this.regionOrign.y+Math.floor(Math.random()*this.regionOrign.y);

        let angle=Math.random()*Math.PI*2;

        let dx=500*Math.cos(angle);

        let dy=Math.sin(angle);

        monster.runAction(
            cc.sequence(
                cc.moveBy(5,dx,dy),cc.callFunc(this.removeNode,this,monster)
        ));


    }
    removeNode(sender,monster){

        this._pool.put(monster);
    }
   
    // update (dt) {}
}
